#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2018/10/29

import numpy as np
import math

#################出行温馨提示#########################

#################一元一次################

def linefit(x , y):
    N = float(len(x))
    sx,sy,sxx,syy,sxy=0,0,0,0,0
    for i in range(0,int(N)):
        sx  += x[i]
        sy  += y[i]
        sxx += x[i]*x[i]
        syy += y[i]*y[i]
        sxy += x[i]*y[i]
    a = (sy*sx/N -sxy)/( sx*sx/N -sxx)
    b = (sy - a*sx)/N
    r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))
    return a,b,r


###################一元二次####################
def f(x):
    return x ** 2 + 1


def f_fit(x, y_fit):
    x = np.array(x)
    a, b, c = y_fit.tolist()
    return a * x ** 2 + b * x + c

############7,15,40区分表达##############################
class Rule(object):
    def __init__(self,day,original_data):
        self.day = day
        self.original_data = original_data

    def rain(self):
        ##判断是否有雨，获取有雨的日期
        wat = self.original_data['weater'].tolist()
        #rain_list = []
        rain_time = []
        weater_lise = []

        for indexs in self.original_data.index:
            weater =  self.original_data.ix[indexs,'weater']
            if '雨' in weater :
                rain_time_pre = self.original_data.ix[indexs,'YBTM']
                weater_lise.append('雨')
                rain_time.append(rain_time_pre)
            else:
                weater_lise.append(weater)
        self.original_data['weater'] = weater_lise
        return rain_time

    def weater_cut(self):
        ##日均温差
        self.original_data['wd_cut']= self.original_data['wd_max']- self.original_data['wd_min']
        self.original_data['wd_cut_gz'] = self.original_data.wd_cut.apply(lambda x: 1 if x >= 7 else 0)
        ##日期保存
        cut_weater_time = self.original_data[self.original_data['wd_cut_gz'] == 1]['YBTM'].apply(
            lambda x: x.strftime("%m-%d:")).tolist()  # %Y-%m-%d

        return cut_weater_time

    def weater_comparison(self):
        ##跟前一天的温度对比
        self.original_data['flu_max'] = self.original_data['wd_max'].astype(int) - self.original_data['wd_max_1'].astype(int)
        self.original_data['flu_min'] = self.original_data['wd_min'].astype(int) - self.original_data['wd_min_1'].astype(int)

        ##最高温--白天的温度对比
        self.original_data['original_low'] = self.original_data.flu_max.apply(lambda x: 1 if x <= -3 else 0)
        self.original_data['original_up'] = self.original_data.flu_max.apply(lambda x: 1 if x >= 3  else 0)

        ##最高温--白天的温度对比
        self.original_data['original_low_night'] = self.original_data.flu_min.apply(lambda x: 1 if x <= -3 else 0)
        self.original_data['original_up_night'] = self.original_data.flu_min.apply(lambda x: 1 if x >= 3 else 0)
        return self.original_data

    def specical_weater(self):
        ###特殊天气
        ts_weater = ['暴雨', '雷阵雨', '大雨', '雪']
        ts_time =[]
        ts_name = []
        for indexs in self.original_data.index:
            weater =  self.original_data.ix[indexs,'weater']
            for ts in ts_weater:
                if ts in weater:
                    ts_time_pre = self.original_data.ix[indexs,'YBTM']
                    ts_name.append(ts)
                    ts_time.append(ts_time_pre)
        return ts_name,ts_time


    def Slope(self):
        ##一元一次方程
        a_max, b1, r1 = linefit(range(len(self.original_data)), self.original_data['wd_max'].astype(int).tolist())
        #test_y_max = [a_max * x + b1 for x in range(len(weater_flu))]

        return a_max

class Expression(Rule):
    #super(B,self).__init__()

    def public(self):
        ##公用的表达
        ts_name, ts_time = self.specical_weater()
        text = '未来{}天'.format(self.day)

        #特殊天气
        if ts_time:
            for x in list(zip(ts_name,ts_time)):
                text += '{},将存在{} \n'.format(x[1],x[0])

        return text



    def simple_day(self):
        text= ''
        original_data = self.weater_comparison()
        ##下雨日期
        rain = self.rain()

        ##温度幅度是否很大
        original_low = original_data[original_data['original_low'] == 1]
        low_time = original_low['YBTM'].tolist()
        original_up = original_data[original_data['original_up'] == 1]
        up_time = original_up['YBTM'].tolist()
        main_weater = self.original_data['weater'].value_counts().index[0]
        if True:
            ##是否下雨，具体到天
            # if len(rain) > 0:
            #     text += '有雨 \n'
            # else:
            #     text += '{}\n'.format(main_weater) #主要天气
            #     #text += '{}有雨\n'.format(','.join(rain))

            ##温度幅度是否很大
            ##白天的变化幅度
            a_text = len(text)
            if len(low_time) > 0:
                text += '{},白天有大幅降温，从{}℃下降到{}℃ \n'.format(','.join(low_time),original_low['wd_max_1'].tolist()[0], original_low['wd_max'].tolist()[0] )

            if len(up_time) > 0:
                if len(low_time) and original_low['YBTM_1'].astype(int).min() < original_low['YBTM_1'].astype(int).min():
                    text_up = '回温'
                else:
                    text_up = '白天有大幅升温'

                text += '{}{}，全天气温{}~{}℃\n'.format(','.join(up_time),text_up, original_up['wd_min'].tolist()[0],
                                                     original_up['wd_max'].tolist()[0])

            ##晚上的变化幅度
            night_data = original_data.loc[(~original_data['original_low'].isin([1])) & (~original_data['original_up'].isin([1]))]

            original_low_night = night_data[night_data['original_low_night'] == 1]
            low_time_night = original_low_night['YBTM'].tolist()

            if len(low_time_night) > 0:
                text += '{},晚上有大幅降温,全天气温{}~{}℃\n'.format(','.join(low_time_night),original_low_night['wd_min'].tolist()[0] , original_low_night['wd_max'].tolist()[0] )

            original_up_night = night_data[night_data['original_up_night'] == 1]
            up_time_night = original_up_night['YBTM'].tolist()
            if len(up_time_night) > 0:
                if len(low_time_night) and original_low_night['YBTM_1'].astype(int).min() < original_up_night['YBTM_1'].astype(int).min():
                    text_up_night = '回温'
                else:
                    text_up_night = '晚上有大幅升温'

                text += '{}{},全天气温{}~{}℃\n'.format(','.join(up_time_night),text_up_night,original_up_night['wd_min'].tolist()[0] , original_up_night['wd_max'].tolist()[0])

            ##如果上面的都没有实现
            if len(text)==0:
                text += '未来{}天，温度整体变幅不大'.format(self.day)


        elif False:
           # text += '{}\n'.format(main_weater)  # 主要天气

            ##白天的整体波动

            if len(original_low)>0 or len(original_up) >0 :
                text += '未来{}天，气温波动较大 \n'.format(self.day)
                if len(original_low) > 0:
                    text += '{}有{}次较大降温过程\n'.format(','.join(low_time) ,len(original_low))
                    data_day_low = original_low['YBTM'].tolist()

                if len(original_up) > 0:
                    if len(original_low) > 0:
                        text_up = '回温'
                    else:
                        text_up = '有较大的升温过程'
                    text += '{}将{}\n'.format(','.join(up_time),text_up)

            text += '夜间气温在{}~{}℃范围内波动 \n'.format(original_data['wd_min'].min(),original_data['wd_min'].max())



        else:

            #未来40天，温度持续降低，白天温度15-25度之间，夜间温度保持在13-18度。
            pass
            # xl = self.Slope()
            # if xl <= -0.2:
            #     #白天降至11℃，夜间降至1℃，请多带御寒衣物。
            #     text += '温度持续降低 \n'
            # elif xl >= 0.2:
            #     text += '温度整体呈上升趋势\n'
            # else:
            #     text += '气温总体平稳\n'
            #
            #     text += '白天温度{}~{}℃之间波动\n'.format(original_data['wd_max'].min(),original_data['wd_max'].max())
            #     text += '夜间温度保持在{}~{}℃\n'.format(original_data['wd_min'].min(),original_data['wd_min'].max())

            ######总体统计---xx次降温/升温，xx次降雨

            # if len(rain) > 0 :
            #     text+= '预计会遇到{}个雨天\n'.format(len(rain) )
            # if len(original_low) >0:
            #     text += '{}次大幅降温,发生在'.format(len(original_low),','.join(low_time))
            #     data_day_low = original_low['YBTM'].tolist()
            #     for dt_low in data_day_low:
            #         dt_data_low = original_low[original_low['YBTM'] == dt_low]
            #         text += '{}(气温{}~{}℃)'.format(dt_low, str(max(dt_data_low['wd_min'])), str(max(dt_data_low['wd_max'])))
            #
            #     min_max_weater = original_data[original_data['wd_max'] == original_data['wd_max'].min()]
            #     text += '\n{}白天气温降至近期最低温{}℃ \n'.format(min_max_weater['YBTM'].tolist()[-1],original_data['wd_max'].min())
            #
            # if len(original_up) >0:
            #     text += '{}次大幅升温'.format(len(original_up))
            #
            #     data_day = original_up['YBTM'].tolist()
            #     for dt in data_day:
            #         dt_data = original_up[original_up['YBTM'] == dt]
            #         text += '({}气温{}~{}℃)'.format(dt, str(max(dt_data['wd_min'])), str(max(dt_data['wd_max'])))

        return text